package org.i9.slb.platform.anseko.console.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * http通信工具类
 *
 * @author R12
 * @version 1.0
 * @date 2018/9/1 11:38
 */
public class HttpUtil {

    /**
     * http post body
     *
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String post(String url, String body) throws Exception {
        SimpleHttpConnectionManager connectionManager = null;
        PostMethod post = null;
        try {
            connectionManager = new SimpleHttpConnectionManager(true);
            // 连接超时,单位毫秒/* 连接超时 */
            connectionManager.getParams().setConnectionTimeout(60 * 1000);
            // 读取超时,单位毫秒/* 请求超时 */
            connectionManager.getParams().setSoTimeout(60000);
            // 设置获取内容编码
            connectionManager.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

            HttpClient client = new HttpClient(new HttpClientParams(), connectionManager);
            post = new PostMethod(url);
            // 设置请求参数的编码
            post.getParams().setContentCharset("UTF-8");

            // 服务端完成返回后，主动关闭链接
            post.setRequestHeader("Connection", "close");
            post.setRequestHeader("Content-Type", "text/plain;chartset=UTF-8");
            StringRequestEntity requestEntity;
            requestEntity = new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8");
            post.setRequestEntity(requestEntity);

            int status = client.executeMethod(post);
            if (status == HttpStatus.SC_OK) {
                String responseResult = post.getResponseBodyAsString();
                return responseResult;
            } else {
                throw new NoHttpResponseException("http响应状态码为 : " + status);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            // 释放链接
            if (post != null) {
                post.releaseConnection();
            }
            // 关闭链接
            if (connectionManager != null) {
                connectionManager.shutdown();
            }
        }
    }
}
